package cn.gz.demo.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;

import java.io.File;

import javax.annotation.Nullable;

import cn.gz.demo.Base64Binding;
import cn.gz.demo.R;
import cn.gz.demo.ui.base.BaseActivity;
import cn.gz.demo.utils.StringUtils;

/**
 * Created by Lyz on 2017/3/8.
 */
public class Base64Activity extends BaseActivity {
    private Base64Binding binding;
    public static final int PICK_PHOTO = 102;
    private String base64;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_base64);

        binding.imageBase64.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //动态申请获取访问 读写磁盘的权限
                if (ContextCompat.checkSelfPermission(Base64Activity.this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(Base64Activity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101);
                } else {
                    //打开相册
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    //Intent.ACTION_GET_CONTENT = "android.intent.action.GET_CONTENT"
                    intent.setType("image/*");
                    startActivityForResult(intent, PICK_PHOTO); // 打开相册
                }

            }
        });

        binding.base64Image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String pPath = Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_DCIM + File.separator + "良策金服" + File.separator; // 文件地址
                File file = new File(pPath);
                // 如果sd卡没有文件夹就创建一个文件夹
                if (!file.exists()) {
                    file.mkdir();
                }
                File pFile = new File(file, System.currentTimeMillis() + ".png");
                if (!TextUtils.isEmpty(base64)) {
//                    StringUtils.base64ToFile(context, base64, "");
                    StringUtils.base64ToFile(base64, pFile.getPath());
//                    StringUtils.base64ToFile(base64, pFile.getPath());
                }
            }
        });
    }


    @SuppressLint("MissingSuperCall")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode) {
            case PICK_PHOTO:
                if (resultCode == RESULT_OK) { // 判断手机系统版本号
                    handleImageOnKitKat(data);
                }
                break;
            default:
                break;
        }
    }

    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是document类型的Uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                // 解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content: //downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是content类型的Uri，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // 如果是file类型的Uri，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        // 根据图片路径显示图片
        displayImage(imagePath);
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过Uri和selection来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void displayImage(String imagePath) {
        base64 = StringUtils.bitmapToString(imagePath, 50, 200, 200);
//        LogUtil.showLog("......length........." + base64.length());
//        LogUtil.showLog(base64);
//        binding.content.setText(base64);

//        if (imagePath != null) {
//            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
//            binding.image.setImageBitmap(bitmap);
//        } else {
//            Toast.makeText(this, "获取相册图片失败", Toast.LENGTH_SHORT).show();
//        }

        if (!TextUtils.isEmpty(base64)) {
            Bitmap bitmap = StringUtils.base64ToBitmap(base64);
            binding.image.setImageBitmap(bitmap);
        }
    }
}
